package org.adw.launcher2.ld.secret.dom.contact;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import org.adw.launcher2.ld.secret.dom.MyContact;
import org.adw.launcher2.ld.secret.dom.MySMS;

import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.OperationApplicationException;
import android.database.Cursor;
import android.os.RemoteException;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.RawContacts;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.provider.ContactsContract.CommonDataKinds.Im;
import android.provider.ContactsContract.CommonDataKinds.Nickname;
import android.provider.ContactsContract.CommonDataKinds.Note;
import android.provider.ContactsContract.CommonDataKinds.Organization;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.CommonDataKinds.StructuredName;
import android.provider.ContactsContract.CommonDataKinds.StructuredPostal;
import android.provider.ContactsContract.CommonDataKinds.Website;
import android.util.Log;

public class ContactAccessor{
	public static String TAG = "ContactAccessorSdk5";

	/**
	 * Returns a Pick Contact intent using the Eclair "contacts" URI.
	 */
	public Intent getPickContactIntent() {
		return new Intent(Intent.ACTION_VIEW, Contacts.CONTENT_URI);
	}

	/**
	 * Retrieves the contact information.
	 */
	public List<UserInfo> loadUserInfos(ContentResolver cr) {
		List<UserInfo> list = new LinkedList<UserInfo>();
		// load name, id, note, nickname , load image of user is not supported
		// yet
		Cursor cursor = cr.query(Contacts.CONTENT_URI, null, null, null, null);
		while (cursor.moveToNext()) {
			String userNote = null;
			String userNickName = null;
			// get user's name
			String userName = cursor.getString(cursor
					.getColumnIndex(Contacts.DISPLAY_NAME));
			// get user's id
			long userId = cursor.getLong(cursor.getColumnIndex(Contacts._ID));
			// get user's note
			String noteWhere = ContactsContract.Data.CONTACT_ID + " = ? AND "
					+ ContactsContract.Data.MIMETYPE + " = ?";
			String[] noteWhereParams = new String[] { userId + "",
					Note.CONTENT_ITEM_TYPE };
			Cursor noteCur = cr.query(ContactsContract.Data.CONTENT_URI, null,
					noteWhere, noteWhereParams, null);
			if (noteCur.moveToFirst()) {
				userNote = noteCur
						.getString(noteCur
								.getColumnIndex(ContactsContract.CommonDataKinds.Note.NOTE));
			}
			noteCur.close();
			// get user's nickname
			String nickNameWhere = ContactsContract.Data.CONTACT_ID
					+ " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
			String[] nickNameWhereParams = new String[] { userId + "",
					Nickname.CONTENT_ITEM_TYPE };
			Cursor nickCursor = cr.query(Data.CONTENT_URI, null, nickNameWhere,
					nickNameWhereParams, null);
			if (nickCursor.moveToFirst()) {
				userNickName = nickCursor
						.getString(nickCursor
								.getColumnIndex(ContactsContract.CommonDataKinds.Nickname.NAME));

			}
			nickCursor.close();
			list.add(new UserInfo(userId, userName, userNote, userNickName));
		}
		cursor.close();
		return list;
	}

	public List<PhoneInfo> loadUserPhones(ContentResolver cr) {
		List<PhoneInfo> list = new LinkedList<PhoneInfo>();
		Cursor cursor = cr.query(Contacts.CONTENT_URI, null, null, null, null);
		while (cursor.moveToNext()) {
			long userId = cursor.getLong(cursor.getColumnIndex(Contacts._ID));
			long hasPhone = cursor.getLong(cursor
					.getColumnIndex(Contacts.HAS_PHONE_NUMBER));
			if (hasPhone > 0) {
				String phoneWhere = Phone.CONTACT_ID + " = ? ";
				String[] phoneWhereParams = new String[] { userId + "" };
				Cursor phoneCursor = cr.query(Phone.CONTENT_URI, null,
						phoneWhere, phoneWhereParams, null);
				while (phoneCursor.moveToNext()) {
					int phoneType = phoneCursor.getInt(phoneCursor
							.getColumnIndex(Phone.TYPE));

					String phoneValue = phoneCursor.getString(phoneCursor
							.getColumnIndex(Phone.NUMBER));
					// Log.d(TAG, userId + "  " +phoneType + "  " + phoneValue);
					list.add(new PhoneInfo(userId, phoneType, phoneValue));
				}
				phoneCursor.close();
			}
		}
		cursor.close();
		return list;
	}

	
	public List<EmailInfo> loadUserEmails(ContentResolver cr) {
		List<EmailInfo> list = new LinkedList<EmailInfo>();
		Cursor cursor = cr.query(Contacts.CONTENT_URI, null, null, null, null);
		while (cursor.moveToNext()) {
			long userId = cursor.getLong(cursor.getColumnIndex(Contacts._ID));
			Cursor emailCur = cr.query(Email.CONTENT_URI, null,
					Email.CONTACT_ID + " = ?", new String[] { userId + "" },
					null);
			while (emailCur.moveToNext()) {
				String email = emailCur.getString(emailCur
						.getColumnIndex(Email.DATA));
				int emailType = emailCur.getInt(emailCur
						.getColumnIndex(Email.TYPE));
				// Log.d(TAG, userId + "  " + email + "  " + emailType);
				list.add(new EmailInfo(userId, emailType, email));

			}
			emailCur.close();
		}
		cursor.close();
		return list;
	}

	
	public List<PostalAddressInfo> loadUserPA(ContentResolver cr) {
		List<PostalAddressInfo> list = new LinkedList<PostalAddressInfo>();
		Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
				null, null, null);
		while (cursor.moveToNext()) {
			long userId = cursor.getLong(cursor.getColumnIndex(Contacts._ID));
			String addrWhere = ContactsContract.Data.CONTACT_ID + " = ? AND "
					+ ContactsContract.Data.MIMETYPE + " = ?";
			String[] addrWhereParams = new String[] {
					userId + "",
					ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE };
			Cursor addrCur = cr.query(ContactsContract.Data.CONTENT_URI, null,
					addrWhere, addrWhereParams, null);
			while (addrCur.moveToNext()) {
				String poBox = addrCur
						.getString(addrCur
								.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POBOX));
				String street = addrCur
						.getString(addrCur
								.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET));
				String city = addrCur
						.getString(addrCur
								.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY));
				String state = addrCur
						.getString(addrCur
								.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.REGION));
				String postalCode = addrCur
						.getString(addrCur
								.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE));
				String country = addrCur
						.getString(addrCur
								.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY));
				String neighbor = addrCur
						.getString(addrCur
								.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.NEIGHBORHOOD));
				int type = addrCur
						.getInt(addrCur
								.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.TYPE));
				list.add(new PostalAddressInfo(userId, type, street, poBox,
						neighbor, city, state, postalCode, country));
				// Log.d(TAG, userId + " " + type + " " +
				// street + " " + poBox + " " +neighbor + " "
				// +city + " " +state + " " +postalCode + " " +country);
			}
			addrCur.close();
		}
		cursor.close();
		return list;
	}

	
	public List<ImInfo> loadUserIm(ContentResolver cr) {
		List<ImInfo> list = new LinkedList<ImInfo>();
		Cursor cursor = cr.query(Contacts.CONTENT_URI, null, null, null, null);
		while (cursor.moveToNext()) {
			long userId = cursor.getLong(cursor.getColumnIndex(Contacts._ID));
			String imWhere = ContactsContract.Data.CONTACT_ID + " = ? AND "
					+ ContactsContract.Data.MIMETYPE + " = ? ";
			String[] imWhereParams = new String[] { userId + "",
					ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE };
			Cursor imCursor = cr.query(ContactsContract.Data.CONTENT_URI, null,
					imWhere, imWhereParams, null);
			while (imCursor.moveToNext()) {
				int imType = imCursor
						.getInt(imCursor
								.getColumnIndex(ContactsContract.CommonDataKinds.Im.PROTOCOL));// AIM
																								// or
																								// Yahoo
																								// or
																								// Gmail
				String imValue = imCursor
						.getString(imCursor
								.getColumnIndex(ContactsContract.CommonDataKinds.Im.DATA));
				// Log.d(TAG, imValue + "  " + imType);
				list.add(new ImInfo(userId, imType, imValue));
			}
			imCursor.close();

		}
		cursor.close();
		return list;
	}

	
	public List<OrganizationInfo> loadUserOrg(ContentResolver cr) {
		List<OrganizationInfo> list = new LinkedList<OrganizationInfo>();
		Cursor cursor = cr.query(Contacts.CONTENT_URI, null, null, null, null);
		while (cursor.moveToNext()) {
			int userId = cursor.getInt(cursor.getColumnIndex(Contacts._ID));
			String orgWhere = ContactsContract.Data.CONTACT_ID + " = ? AND "
					+ ContactsContract.Data.MIMETYPE + " = ? ";
			String[] orgWhereParams = new String[] {
					userId + "",
					ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE };
			Cursor orgCursor = cr.query(ContactsContract.Data.CONTENT_URI,
					null, orgWhere, orgWhereParams, null);
			while (orgCursor.moveToNext()) {
				String companyName = orgCursor
						.getString(orgCursor
								.getColumnIndex(ContactsContract.CommonDataKinds.Organization.DATA));
				String companyTitle = orgCursor
						.getString(orgCursor
								.getColumnIndex(ContactsContract.CommonDataKinds.Organization.TITLE));
				int type = orgCursor
						.getInt(orgCursor
								.getColumnIndex(ContactsContract.CommonDataKinds.Organization.TYPE));
				// Log.d(TAG, companyTitle + " " + companyName + " " + type);
				list.add(new OrganizationInfo(userId, type, companyName,
						companyTitle));
			}
		}
		cursor.close();
		return list;
	}

	
	public List<WebsiteInfo> loadUserWebsite(ContentResolver cr) {
		List<WebsiteInfo> list = new LinkedList<WebsiteInfo>();
		Cursor cursor = cr.query(Contacts.CONTENT_URI, null, null, null, null);
		while (cursor.moveToNext()) {
			long userId = cursor.getInt(cursor.getColumnIndex(Contacts._ID));
			String websiteWhere = ContactsContract.Data.CONTACT_ID
					+ " = ? AND " + ContactsContract.Data.MIMETYPE + " = ? ";
			String[] websiteWhereParams = new String[] { userId + "",
					ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE };
			Cursor webCursor = cr.query(ContactsContract.Data.CONTENT_URI,
					null, websiteWhere, websiteWhereParams, null);
			while (webCursor.moveToNext()) {
				String websiteName = webCursor
						.getString(webCursor
								.getColumnIndex(ContactsContract.CommonDataKinds.Website.URL));
				list.add(new WebsiteInfo(userId, websiteName));
				// Log.d(TAG, websiteName + " " + userId);
				webCursor.close();
			}
		}
		cursor.close();
		return list;
	}

	
	public UserInfo loadUserInfos(ContentResolver cr, long userId) {

		String userNote = null;
		String userNickName = null;
		String userName = null;
		// get user's name
		Cursor cursor = cr.query(Contacts.CONTENT_URI, null, Contacts._ID
				+ " = ? ", new String[] { userId + "" }, null);
		if (cursor.moveToFirst()) {
			userName = cursor.getString(cursor
					.getColumnIndex(Contacts.DISPLAY_NAME));
			// Log.d(TAG, userName);
		}
		cursor.close();
		// get user's note
		String noteWhere = ContactsContract.Data.CONTACT_ID + " = ? AND "
				+ ContactsContract.Data.MIMETYPE + " = ?";
		String[] noteWhereParams = new String[] { userId + "",
				Note.CONTENT_ITEM_TYPE };
		Cursor noteCur = cr.query(ContactsContract.Data.CONTENT_URI, null,
				noteWhere, noteWhereParams, null);
		if (noteCur.moveToFirst()) {
			userNote = noteCur
					.getString(noteCur
							.getColumnIndex(ContactsContract.CommonDataKinds.Note.NOTE));
		}
		noteCur.close();
		// get user's nickname
		String nickNameWhere = ContactsContract.Data.CONTACT_ID + " = ? AND "
				+ ContactsContract.Data.MIMETYPE + " = ?";
		String[] nickNameWhereParams = new String[] { userId + "",
				Nickname.CONTENT_ITEM_TYPE };
		Cursor nickCursor = cr.query(Data.CONTENT_URI, null, nickNameWhere,
				nickNameWhereParams, null);
		if (nickCursor.moveToFirst()) {
			userNickName = nickCursor
					.getString(nickCursor
							.getColumnIndex(ContactsContract.CommonDataKinds.Nickname.NAME));

		}
		nickCursor.close();
		return new UserInfo(userId, userName, userNote, userNickName);
	}

	
	public List<EmailInfo> loadUserEmails(ContentResolver cr, long userId) {
		List<EmailInfo> list = new LinkedList<EmailInfo>();
		Cursor emailCur = cr.query(Email.CONTENT_URI, null, Email.CONTACT_ID
				+ " = ?", new String[] { userId + "" }, null);
		while (emailCur.moveToNext()) {
			String email = emailCur.getString(emailCur
					.getColumnIndex(Email.DATA));
			int emailType = emailCur
					.getInt(emailCur.getColumnIndex(Email.TYPE));
			// Log.d(TAG, userId + "  " + email + "  " + emailType);
			list.add(new EmailInfo(userId, emailType, email));

		}
		emailCur.close();
		return list;
	}

	
	public List<ImInfo> loadUserIm(ContentResolver cr, long userId) {
		List<ImInfo> list = new LinkedList<ImInfo>();
		String imWhere = ContactsContract.Data.CONTACT_ID + " = ? AND "
				+ ContactsContract.Data.MIMETYPE + " = ? ";
		String[] imWhereParams = new String[] { userId + "",
				ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE };
		Cursor imCursor = cr.query(ContactsContract.Data.CONTENT_URI, null,
				imWhere, imWhereParams, null);
		while (imCursor.moveToNext()) {
			int imType = imCursor
					.getInt(imCursor
							.getColumnIndex(ContactsContract.CommonDataKinds.Im.PROTOCOL));// AIM
			String imValue = imCursor.getString(imCursor
					.getColumnIndex(ContactsContract.CommonDataKinds.Im.DATA));
			// Log.d(TAG, imValue + "  " + imType);
			list.add(new ImInfo(userId, imType, imValue));
		}
		imCursor.close();
		return list;
	}

	
	public List<OrganizationInfo> loadUserOrg(ContentResolver cr, long userId) {
		List<OrganizationInfo> list = new LinkedList<OrganizationInfo>();
		String orgWhere = ContactsContract.Data.CONTACT_ID + " = ? AND "
				+ ContactsContract.Data.MIMETYPE + " = ? ";
		String[] orgWhereParams = new String[] { userId + "",
				ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE };
		Cursor orgCursor = cr.query(ContactsContract.Data.CONTENT_URI, null,
				orgWhere, orgWhereParams, null);
		while (orgCursor.moveToNext()) {
			String companyName = orgCursor
					.getString(orgCursor
							.getColumnIndex(ContactsContract.CommonDataKinds.Organization.DATA));
			String companyTitle = orgCursor
					.getString(orgCursor
							.getColumnIndex(ContactsContract.CommonDataKinds.Organization.TITLE));
			int type = orgCursor
					.getInt(orgCursor
							.getColumnIndex(ContactsContract.CommonDataKinds.Organization.TYPE));
			list.add(new OrganizationInfo(userId, type, companyName,
					companyTitle));
		}
		return list;
	}

	
	public List<PostalAddressInfo> loadUserPA(ContentResolver cr, long userId) {
		List<PostalAddressInfo> list = new LinkedList<PostalAddressInfo>();

		String addrWhere = ContactsContract.Data.CONTACT_ID + " = ? AND "
				+ ContactsContract.Data.MIMETYPE + " = ?";
		String[] addrWhereParams = new String[] {
				userId + "",
				ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE };
		Cursor addrCur = cr.query(ContactsContract.Data.CONTENT_URI, null,
				addrWhere, addrWhereParams, null);
		while (addrCur.moveToNext()) {
			String poBox = addrCur
					.getString(addrCur
							.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POBOX));
			String street = addrCur
					.getString(addrCur
							.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET));
			String city = addrCur
					.getString(addrCur
							.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY));
			String state = addrCur
					.getString(addrCur
							.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.REGION));
			String postalCode = addrCur
					.getString(addrCur
							.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE));
			String country = addrCur
					.getString(addrCur
							.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY));
			String neighbor = addrCur
					.getString(addrCur
							.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.NEIGHBORHOOD));
			int type = addrCur
					.getInt(addrCur
							.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.TYPE));
			list.add(new PostalAddressInfo(userId, type, street, poBox,
					neighbor, city, state, postalCode, country));
		}
		addrCur.close();
		return list;
	}

	
	public List<PhoneInfo> loadUserPhones(ContentResolver cr, long userId) {
		List<PhoneInfo> list = new LinkedList<PhoneInfo>();

		String phoneWhere = Phone.CONTACT_ID + " = ? ";
		String[] phoneWhereParams = new String[] { userId + "" };
		Cursor phoneCursor = cr.query(Phone.CONTENT_URI, null, phoneWhere,
				phoneWhereParams, null);
		while (phoneCursor.moveToNext()) {
			int phoneType = phoneCursor.getInt(phoneCursor
					.getColumnIndex(Phone.TYPE));

			String phoneValue = phoneCursor.getString(phoneCursor
					.getColumnIndex(Phone.NUMBER));
			Log.d("loadUserPhones", userId + "  " + phoneType + "  "
					+ phoneValue);
			list.add(new PhoneInfo(userId, phoneType, phoneValue));
			phoneCursor.close();
		}
		return list;
	}

	
	public List<WebsiteInfo> loadUserWebsite(ContentResolver cr, long userId) {
		List<WebsiteInfo> list = new LinkedList<WebsiteInfo>();
		String websiteWhere = ContactsContract.Data.CONTACT_ID + " = ? AND "
				+ ContactsContract.Data.MIMETYPE + " = ? ";
		String[] websiteWhereParams = new String[] { userId + "",
				ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE };
		Cursor webCursor = cr.query(ContactsContract.Data.CONTENT_URI, null,
				websiteWhere, websiteWhereParams, null);
		while (webCursor.moveToNext()) {
			String websiteName = webCursor
					.getString(webCursor
							.getColumnIndex(ContactsContract.CommonDataKinds.Website.URL));
			list.add(new WebsiteInfo(userId, websiteName));
			// Log.d(TAG, websiteName + " " + userId);
			webCursor.close();
		}
		return list;
	}

	/**
	 * Retrieves the contact information.
	 */

	
	public void insertAllInfoOfOneUser(ContentResolver cr, UserInfo userInfo,
			List<PhoneInfo> listPhone, List<EmailInfo> listEmail,
			List<PostalAddressInfo> listPA, List<OrganizationInfo> listOrg,
			List<ImInfo> listIm, List<WebsiteInfo> listWeb) {
		ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
		int rawContactId = ops.size();
		// prepare data to insert
		int id = (int) userInfo.getUserId();
		prepareToInsert(ops, id);
		prepareUserInfo(userInfo, ops, rawContactId);
		preparePhone(listPhone, ops, rawContactId);
		prepareEmail(listEmail, ops, rawContactId);
		preparePA(listPA, ops, rawContactId);
		prepareOrg(listOrg, ops, rawContactId);
		prepareIm(listIm, ops, rawContactId);
		prepareWebsite(listWeb, ops, rawContactId);

		// insert
		try {
			cr.applyBatch(ContactsContract.AUTHORITY, ops);
		} catch (RemoteException e) {
			e.printStackTrace();
		} catch (OperationApplicationException e) {
			e.printStackTrace();
		}

	}

	public void prepareToInsert(ArrayList<ContentProviderOperation> ops, int id) {
		ops.add(ContentProviderOperation.newInsert(RawContacts.CONTENT_URI)
				.withValue(RawContacts.ACCOUNT_TYPE, null).withValue(
						RawContacts.ACCOUNT_NAME, null).build());
		Log.d("Prepare to insert", id + "");
	}

	// cac ham prepare deu chi moi prepare data, sau khi prepare du 7 Table ta
	// moi bat dau chay lenh insert o ham
	public void prepareUserInfo(UserInfo userInfo,
			ArrayList<ContentProviderOperation> ops, int rawContactId) {
		ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
				.withValueBackReference(Data.RAW_CONTACT_ID, rawContactId)
				.withValue(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE)
				.withValue(StructuredName.DISPLAY_NAME, userInfo.getUserName())
				.build());

		ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
				.withValueBackReference(Data.RAW_CONTACT_ID, rawContactId)
				.withValue(Data.MIMETYPE, Note.CONTENT_ITEM_TYPE).withValue(
						Note.NOTE, userInfo.getUserNote()).build());

		ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
				.withValueBackReference(Data.RAW_CONTACT_ID, rawContactId)
				.withValue(Data.MIMETYPE, Nickname.CONTENT_ITEM_TYPE)
				.withValue(Nickname.NAME, userInfo.getUserNickname()).build());
	}

	public void preparePhone(List<PhoneInfo> listPhone,
			ArrayList<ContentProviderOperation> ops, int rawContactId) {
		for (int i = 0; i < listPhone.size(); i++) {
			ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
					.withValueBackReference(Data.RAW_CONTACT_ID, rawContactId)
					.withValue(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE)
					.withValue(Phone.NUMBER, listPhone.get(i).getValue())
					.withValue(Phone.TYPE, listPhone.get(i).getType()).build());
		}
	}

	public void prepareEmail(List<EmailInfo> listEmail,
			ArrayList<ContentProviderOperation> ops, int rawContactId) {
		for (int i = 0; i < listEmail.size(); i++) {
			ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
					.withValueBackReference(Data.RAW_CONTACT_ID, rawContactId)
					.withValue(Data.MIMETYPE, Email.CONTENT_ITEM_TYPE)
					.withValue(Email.DATA, listEmail.get(i).getValue())
					.withValue(Email.TYPE, listEmail.get(i).getType()).build());
		}
	}

	public void preparePA(List<PostalAddressInfo> listPA,
			ArrayList<ContentProviderOperation> ops, int rawContactId) {
		for (int i = 0; i < listPA.size(); i++) {
			PostalAddressInfo pa = listPA.get(i);
			ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
					.withValueBackReference(Data.RAW_CONTACT_ID, rawContactId)
					.withValue(Data.MIMETYPE,
							StructuredPostal.CONTENT_ITEM_TYPE).withValue(
							StructuredPostal.TYPE, pa.getType()).withValue(
							StructuredPostal.STREET, pa.getStreet()).withValue(
							StructuredPostal.POBOX, pa.getPoBox()).withValue(
							StructuredPostal.NEIGHBORHOOD, pa.getNeighbor())
					.withValue(StructuredPostal.CITY, pa.getCity()).withValue(
							StructuredPostal.REGION, pa.getState()).withValue(
							StructuredPostal.POSTCODE, pa.getZipcode())
					.withValue(StructuredPostal.COUNTRY, pa.getCountry())
					.build());
		}
	}

	public void prepareIm(List<ImInfo> listIm,
			ArrayList<ContentProviderOperation> ops, int rawContactId) {
		for (int i = 0; i < listIm.size(); i++) {
			ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
					.withValueBackReference(Data.RAW_CONTACT_ID, rawContactId)
					.withValue(Data.MIMETYPE, Im.CONTENT_ITEM_TYPE).withValue(
							Im.PROTOCOL, listIm.get(i).getType()).withValue(
							Im.DATA, listIm.get(i).getValue()).build());
		}
	}

	public void prepareOrg(List<OrganizationInfo> listOrg,
			ArrayList<ContentProviderOperation> ops, int rawContactId) {
		for (int i = 0; i < listOrg.size(); i++) {
			ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
					.withValueBackReference(Data.RAW_CONTACT_ID, rawContactId)
					.withValue(Data.MIMETYPE, Organization.CONTENT_ITEM_TYPE)
					.withValue(Organization.TYPE, listOrg.get(i).getType())
					.withValue(Organization.DATA, listOrg.get(i).getCompany())
					.withValue(Organization.TITLE, listOrg.get(i).getTitle())
					.build());
		}
	}

	public void prepareWebsite(List<WebsiteInfo> listWeb,
			ArrayList<ContentProviderOperation> ops, int rawContactId) {
		for (int i = 0; i < listWeb.size(); i++) {
			ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
					.withValueBackReference(Data.RAW_CONTACT_ID, rawContactId)
					.withValue(Data.MIMETYPE, Website.CONTENT_ITEM_TYPE)
					.withValue(Website.URL, listWeb.get(i).getValue()).build());
		}
	}

	
	public List<MyContact> loadContactInfo(ContentResolver cr) {// load all info
																// of all user
		List<MyContact> list = new LinkedList<MyContact>();
		Cursor cursor = cr.query(Contacts.CONTENT_URI, null, null, null, null);
		while (cursor.moveToNext()) {
			long userId = cursor.getInt(cursor.getColumnIndex(Contacts._ID));
			UserInfo userInfo = loadUserInfos(cr, userId);
			List<EmailInfo> listEmail = loadUserEmails(cr, userId);
			List<PhoneInfo> listPhone = loadUserPhones(cr, userId);
			List<PostalAddressInfo> listPA = loadUserPA(cr, userId);
			List<OrganizationInfo> listOrg = loadUserOrg(cr, userId);
			List<ImInfo> listIm = loadUserIm(cr, userId);
			List<WebsiteInfo> listWeb = loadUserWebsite(cr, userId);
			MyContact myContact = new MyContact(userInfo, listPhone, listEmail,
					listPA, listOrg, listIm, listWeb);
			// assign myContact ID = userId
			myContact.id = userId;
			list.add(myContact);
		}
		cursor.close();
		return list;
	}

	
	public void deleteUser(ContentResolver cr, long id) {
		ArrayList ops = new ArrayList();
		String[] args = new String[] { id + "" };
		ops.add(ContentProviderOperation.newDelete(RawContacts.CONTENT_URI)
				.withSelection(RawContacts.CONTACT_ID + "=?", args).build());
		try {
			cr.applyBatch(ContactsContract.AUTHORITY, ops);
		} catch (RemoteException e) {
			e.printStackTrace();
		} catch (OperationApplicationException e) {
			e.printStackTrace();
		}
	}

	
	public List<UserInfo> loadUserInfosForAdapter(ContentResolver cr) {
		List<UserInfo> list = new LinkedList<UserInfo>();
		Cursor cursor = cr.query(Contacts.CONTENT_URI, 
				new String[]{"_id", "display_name"}, null, null, null);
		while (cursor.moveToNext()) {
			String userNote = null;
			String userNickName = null;
			String userName = cursor.getString(cursor.getColumnIndex(Contacts.DISPLAY_NAME));
			long userId = cursor.getLong(cursor.getColumnIndex(Contacts._ID));
			
			list.add(new UserInfo(userId, userName, userNote, userNickName));
		}
		cursor.close();
		return list;
	}
	
//	public List<MySMS> loadUserForSMSDisplay(ContentResolver cr) {
//		List<MySMS> list = new LinkedList<MySMS>();
//		Cursor cursor = cr.query(Contacts.CONTENT_URI, 
//				new String[]{"_id", "display_name"}, null, null, null);
//		Cursor phoneCursor = null;
//		while (cursor.moveToNext()) {
//			String userName = cursor.getString(cursor.getColumnIndex(Contacts.DISPLAY_NAME));//user name
//			long userId = cursor.getLong(cursor.getColumnIndex(Contacts._ID));//id
//			String phoneWhere = Phone.CONTACT_ID + " = ? ";
//			String[] phoneWhereParams = new String[] { userId + "" };
//			phoneCursor = cr.query(Phone.CONTENT_URI, new String[]{Phone.NUMBER}, phoneWhere,
//					phoneWhereParams, null);
//			String phoneValue = "";
//			if (phoneCursor.moveToFirst()) {
//				phoneValue = phoneCursor.getString(phoneCursor
//						.getColumnIndex(Phone.NUMBER));
//			}
//			list.add(new MySMS(userId, userName,phoneValue));
//		}
//		phoneCursor.close();
//		cursor.close();
//		return list;
//	}
	
	

}
